package com.example.service;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    //这里先不深入了解生命周期
    private ServiceConnection  mServiceConnection;
    private MyService.MyBinder mServiceBinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent= new Intent(this, MyService.class);
        startService(intent);//stopService(intent);
        mServiceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {//绑定成功
                Log.d("myservice", "Connected");
                mServiceBinder = (MyService.MyBinder) service;//获取Service(似乎也可以让binder返回一个service，然会调用servi里的public类
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {//绑定失败
                Log.d("myservice", "Disconnected");
            }
        };
        bindService(intent, mServiceConnection, BIND_AUTO_CREATE);//绑定Service

        //Service的启动绑定要一定时间，到这里还没有完成


        findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mServiceBinder == null) {
                    Log.d("myservice", "error");
                } else {
                    mServiceBinder.xxx();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mServiceConnection);//解绑
    }
}